package org.wyw.utils;

import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;

public class MoneyUtil {
    /**
     * 汉语中数字大写
     */
    private static final String[] CN_UPPER_NUMBER = { "零", "壹", "贰", "叁", "肆",
            "伍", "陆", "柒", "捌", "玖" };
    /**
     * 汉语中货币单位大写，这样的设计类似于占位符
     */
    private static final String[] CN_UPPER_MONETRAY_UNIT = { "分", "角", "元",
            "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "兆", "拾",
            "佰", "仟" };

    private static final String CBit[] = {"", "拾", "佰", "仟"};

    /**
     * 特殊字符：整
     */
    private static final String CN_FULL = "整";
    /**
     * 特殊字符：负
     */
    private static final String CN_NEGATIVE = "负";
    /**
     * 金额的精度，默认值为2
     */
    private static final int MONEY_PRECISION = 2;
    /**
     * 特殊字符：零元整
     */
    private static final String CN_ZEOR_FULL = "零元" + CN_FULL;

    /**
     *  金额字符串转为 BigDecimal
     * @param money  金额字符串
     * @return
     */
    public static BigDecimal toBigDecimal(String money) {
        return toBigDecimal(money, null, null);
    }

    /**
     *  金额字符串转为 BigDecimal
     * @param money  金额字符串
     * @param regex  regex
     * @return
     */
    public static BigDecimal toBigDecimal(String money, String regex) {
        return toBigDecimal(money, regex, "");
    }

    /**
     *  金额字符串转为 BigDecimal
     * @param money  金额字符串
     * @param regex  regex
     * @param replacement  replacement
     * @return
     */
    public static BigDecimal toBigDecimal(String money, String regex, String replacement) {
        if (StringUtils.isEmpty(money)) {
            return BigDecimal.ZERO;
        }

        if (StringUtils.isEmpty(regex) || replacement == null) {
            return new BigDecimal(money);
        }

        return new BigDecimal(money.replaceAll(regex, replacement));
    }

    // 金额转换为大写(含'元整')
    public static String number2CNMontrayUnit(BigDecimal numberOfMoney) {
        StringBuffer sb = new StringBuffer();
        // -1, 0, or 1 as the value of this BigDecimal is negative, zero, or
        // positive.
        int signum = numberOfMoney.signum();
        // 零元整的情况
        if (signum == 0) {
            return CN_ZEOR_FULL;
        }
        // 这里会进行金额的四舍五入
        long number = numberOfMoney.movePointRight(MONEY_PRECISION)
                .setScale(0, 4).abs().longValue();
        // 得到小数点后两位值
        long scale = number % 100;
        int numUnit = 0;
        int numIndex = 0;
        boolean getZero = false;
        // 判断最后两位数，一共有四中情况：00 = 0, 01 = 1, 10, 11
        if (!(scale > 0)) {
            numIndex = 2;
            number = number / 100;
            getZero = true;
        }
        if ((scale > 0) && (!(scale % 10 > 0))) {
            numIndex = 1;
            number = number / 10;
            getZero = true;
        }
        int zeroSize = 0;
        while (true) {
            if (number <= 0) {
                break;
            }
            // 每次获取到最后一个数
            numUnit = (int) (number % 10);
            if (numUnit > 0) {
                if ((numIndex == 9) && (zeroSize >= 3)) {
                    sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]);
                }
                if ((numIndex == 13) && (zeroSize >= 3)) {
                    sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]);
                }
                sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                sb.insert(0, CN_UPPER_NUMBER[numUnit]);
                getZero = false;
                zeroSize = 0;
            } else {
                ++zeroSize;
                if (!(getZero)) {
                    sb.insert(0, CN_UPPER_NUMBER[numUnit]);
                }
                if (numIndex == 2) {
                    if (number > 0) {
                        sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                    }
                } else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0)) {
                    sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                }
                getZero = true;
            }
            // 让number每次都去掉最后一个数
            number = number / 10;
            ++numIndex;
        }
        // 如果signum == -1，则说明输入的数字为负数，就在最前面追加特殊字符：负
        if (signum == -1) {
            sb.insert(0, CN_NEGATIVE);
        }
        // 输入的数字小数点后两位为"00"的情况，则要在最后追加特殊字符：整
        if (!(scale > 0)) {
            sb.append(CN_FULL);
        }
        return sb.toString();
    }

    // 金额转换为大写(不含'元整')
    public static String rmbChange(String rmb) {
        if (!rmb.contains(".")){
            return capitalization(rmb);
        }else {
            //修复bug，入参格式不对的情况下
            rmb = new java.text.DecimalFormat("#.00").format(Double.parseDouble(rmb));
            int index = rmb.indexOf('.');
            if ("00".equals(rmb.substring(index + 1, index + 3))){
                return capitalization(rmb.substring(0, index));
            }else {
                return capitalization(rmb.substring(0, index)) + "元"
                        + capitalization(String.valueOf(getNumByte(rmb, -1))) + "角"
                        + capitalization(String.valueOf(getNumByte(rmb, -2))) + "分";
            }
        }
    }

    public static char getNumByte(String szNum, int nBit) {
        int sl = szNum.length();
        int nPos = 0;
        while (nPos < sl && szNum.charAt(nPos) != '.')
            nPos++;
        if (nBit < 0)
            nPos = nPos - nBit;
        else
            nPos = nPos - nBit - 1;
        if (nPos < 0 || nPos >= sl)
            return '0';
        return szNum.charAt(nPos);
    }

    public static String capitalization(String szNum) {
        StringBuilder resstr = new StringBuilder();
        String tmpstr = szNum.trim();
        int sl = tmpstr.length();
        int sp = 0;
        int dotpos = tmpstr.indexOf('.');
        if (dotpos != -1) {
            while (sl > 1 && tmpstr.charAt(sl - 1) == '0')
                sl--;
            if (tmpstr.charAt(sl - 1) == '.')
                sl--;
            if (sl != tmpstr.length()) {
                tmpstr = tmpstr.substring(0, sl);
            }
        } else {
            dotpos = sl;
        }
        if (sl < 1)
            return CN_UPPER_NUMBER[0];
        if (tmpstr.charAt(0) == '-') {
            resstr.append("负");
            sp = 1;
        }
        String integerNum = tmpstr.substring(sp, dotpos - sp);
        String decimalNum = "";
        if (dotpos + 1 < sl)
            decimalNum = tmpstr.substring(dotpos + 1);
        sl = integerNum.length();
        sp = 0;
        while (sp < sl && integerNum.charAt(sp) == '0')
            sp++;
        if (sp > 0)
            integerNum = integerNum.substring(sp);
        int inl = integerNum.length();
        if (inl > 0) {
            int h = (inl - 1) % 4;
            int j = (inl - 1) / 4 + 1;
            sp = 0;
            boolean allzero = false;
            boolean preallzero = false;
            for (; j > 0; j--) {
                int k = h;
                h = 3;
                boolean preiszero = allzero;
                allzero = true;
                for (; k >= 0; k--, sp++) {
                    if (integerNum.charAt(sp) == '0')
                        preiszero = true;
                    else {
                        allzero = false;
                        if (preiszero)
                            resstr.append("零");
                        preiszero = false;
                        resstr.append(CN_UPPER_NUMBER[(byte) (integerNum.charAt(sp)) - 48]).append(CBit[k]);
                    }
                }
                if (j % 2 == 0) {
                    if (!allzero)
                        resstr.append("万");
                } else {
                    if (!allzero || !preallzero) {
                        int repyi = j / 2;
                        for (int i = 0; i < repyi; i++)
                            resstr.append("亿");
                    }
                }
                preallzero = allzero;
            }
        } else {
            resstr.append("零");
        }
        int dnl = decimalNum.length();
        if (dnl > 0) {
            resstr.append("点");
            for (int i = 0; i < dnl; i++) {
                resstr.append(CN_UPPER_NUMBER[(byte) (decimalNum.charAt(i)) - 48]);
            }
        }
        return resstr.toString();
    }
}
